//
//  MainTabBarController.swift
//  weibo
//
//  Created by tomato on 2021/9/8.
//

import UIKit

class MainTabBarController: UITabBarController {

    //MARK: - 懒加载控件： 加号button
    private lazy var composeBtn:UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
         backImageName: "tabbar_compose_button")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //添加4个主页面
        setupChilderViewController()
        //设置中间的的加号按钮
        setUpComposeButton()
    }
    
    // 添加中间的加号按钮
    override func viewWillAppear(_ animated: Bool) {
        //3、即将出现  //会创建tabbar中所有控制器对应的按钮
         super.viewWillAppear(animated)
        //将添加按钮弄到前面
        tabBar.bringSubviewToFront(composeBtn)
     }
    
    
    //添加按钮
    private func setUpComposeButton(){
          
        tabBar.addSubview(composeBtn)
        //调整布局
        let count = children.count
        //让按钮宽一点点，能够解决手指触摸的容错问题
        let width = tabBar.bounds.width/CGFloat(count)-1
        let rect = CGRect(x: 0, y: 0, width: width, height: tabBar.bounds.height)
        //3.设置按钮frame和偏移位
        composeBtn.frame = rect.offsetBy(dx: width * 2, dy: 0)
        
        //添加点击事件
        composeBtn.addTarget(self, action: #selector(self.clickComposeBtn), for: .touchUpInside)
    }
    
    //MARK: - btn添加事件
    //如果单纯使用private运行循环将无法正确发送消息，导致崩溃
    //如果使用@objc修饰符号，可以保证运行循环能够发送此消息，
    @objc private func clickComposeBtn(){
        
//        print("点我了")
    }
    
}


// MARK: - 设置界面
extension UITabBarController {
    
    /// 设置tabbar子控制器
    func setupChilderViewController() {
        // 首页
        let homeVC = HomeViewController()
        addChildViewController(controller: homeVC, title: "首页", imageName: "tabbar_home")
        // 消息
        let messageVC = MessageViewController()
        addChildViewController(controller: messageVC, title: "消息", imageName: "tabbar_message_center")
        addChild(UIViewController())
        // 发现
        let discoveryVC = DiscoverViewController()
        addChildViewController(controller: discoveryVC, title: "发现", imageName: "tabbar_discover")
        // 我
        let profileVC = ProfileViewController()
        addChildViewController(controller: profileVC, title: "我", imageName: "tabbar_profile")
    }
    
    /// 添加子控制器,设置标题和图片名称,并且包装导航控制器
    func addChildViewController(controller: UIViewController, title: String, imageName: String) {
        // 设置标题
        controller.title = title
        // 设置tabbar图片
        controller.tabBarItem.image = UIImage(named: imageName)
        // 设置高亮图片
        controller.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
        // 设置文字选中的颜色
        controller.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.orange], for: UIControl.State.selected)
        self.addChild(UINavigationController(rootViewController: controller))
    }
    
    
}

